package secret.hehe.com.secret.Util;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.UUID;

import secret.hehe.com.secret.R;
import secret.hehe.com.secret.db.DatabaseHelper;



public class Util {
    public static Bitmap makeRoundImage(Bitmap bitmap)
    {
        //圆形图片
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }
        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        int color= 0xffff0000;
        Paint paint = new Paint();
        Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
        Rect dst= new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
        RectF rectF = new RectF(dst);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }
    public static void startWebView(WebView webView, String webUrl, RelativeLayout relativeLayout){
        //加载webview
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        webView.setLayoutParams(layoutParams);
        //webView.setWebContentsDebuggingEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);
        //webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        //webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.loadUrl(webUrl);
        webView.requestFocusFromTouch();
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        webView.setOnLongClickListener(new View.OnLongClickListener() {//长按事件

            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        relativeLayout.addView(webView);
    }
    public static void destroyWebView(WebView webView){
        //销毁webview
        try {
            if (webView != null) {
                ViewParent parent = webView.getParent();
                if (parent != null) {
                    ((ViewGroup) parent).removeView(webView);
                }
                webView.stopLoading();
                // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
                webView.getSettings().setJavaScriptEnabled(false);
                webView.clearHistory();
                webView.clearView();
                webView.removeAllViews();
                webView.destroy();
                webView = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static JSONArray doSelect(String name, String where, Context context){
        //数据库查询操作
        JSONArray jsonArray=new JSONArray();
        DatabaseHelper dbHelper = new DatabaseHelper(context, "my.db", null, 1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
            String sql="select *  from "+name+" where "+where;
            Cursor cursor = db.rawQuery(sql, null);
            if (cursor.moveToFirst()) {
                do {
                    int totalColumn = cursor.getColumnCount();
                    JSONObject jsonObject = new JSONObject();
                    for(int i = 0 ; i < totalColumn;i++){
                        if( cursor.getColumnName(i) != null )
                        {
                            try {
                                if( cursor.getString(i) != null ) {
                                    jsonObject.put(cursor.getColumnName(i) ,  cursor.getString(i) );
                                }
                                else {
                                    jsonObject.put( cursor.getColumnName(i) ,  "" );
                                }
                            }catch( Exception e ) {
                                e.printStackTrace();
                            }
                        }
                    }
                jsonArray.put(jsonObject);
                } while (cursor.moveToNext());
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            db.close();
        }
        return jsonArray;
    }
    public static void doUpdate(String name, JSONArray jsonArray, Context context){
        //存在则更新，不存在则插入
        DatabaseHelper dbHelper = new DatabaseHelper(context, "my.db", null, 1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            for(int i =0;i<jsonArray.length();i++){
                JSONObject jsonObject =(JSONObject) jsonArray.opt(i);
                Iterator it = jsonObject.keys();
                String values = "";
                String name_list = "";
                while (it.hasNext()){
                    String key = it.next().toString();
                    String value = jsonObject.getString(key);
                    name_list+=key+",";
                    values+="'"+value+"',";
                }
                name_list = name_list.substring(0,name_list.length()-1);
                values = values.substring(0,values.length()-1);
                String sql = "insert or ignore into "+name+"("+name_list+") values ("+values+')';
                db.execSQL(sql);
            }
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            db.endTransaction();
            db.close();
        }
    }
    public static void doInsert(String name, JSONArray jsonArray, Context context){
        //存在则忽视，不存在则插入
        DatabaseHelper dbHelper = new DatabaseHelper(context, "my.db", null, 1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            for(int i =0;i<jsonArray.length();i++){
                JSONObject jsonObject =(JSONObject) jsonArray.opt(i);
                Iterator it = jsonObject.keys();
                String values = "";
                String name_list = "";
                while (it.hasNext()){
                    String key = it.next().toString();
                    String value = jsonObject.getString(key);
                    name_list+=key+",";
                    values+="'"+value+"',";
                }
                name_list = name_list.substring(0,name_list.length()-1);
                values = values.substring(0,values.length()-1);
                String sql = "insert or ignore into "+name+"("+name_list+") values ("+values+')';
                db.execSQL(sql);
            }
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            db.endTransaction();
            db.close();
        }
    }
    public static void doDelete(String name, String where, Context context){
        //数据库删除
        DatabaseHelper dbHelper = new DatabaseHelper(context, "my.db", null, 1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
            String sql="DELETE  from "+name+" where "+where;
            db.execSQL(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            db.close();
        }
    }
    public static int pxtodip(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    public static void changeImg(int account,ImageView imageView,Context context){
        //修改头像
        if(account<0||account>R.integer.head_count)
            account=0;
        InputStream icon_stream = context.getResources().openRawResource(R.drawable.icon00+ account);
        Bitmap bitmap = makeRoundImage(BitmapFactory.decodeStream(icon_stream));
        imageView.setImageBitmap(bitmap);
    }
    public static String getPath(ContentResolver contentResolver, Uri uri) {
        //获取文件路径
        String[] projection = {MediaStore.Images.Media.DATA };
        Cursor cursor = contentResolver.query(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndex(projection[0]);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    public static Bitmap setImageSize(String path, EditText message_text){
        BitmapFactory.Options opt = new BitmapFactory.Options();
        //加载图片
        Bitmap bm = BitmapFactory.decodeFile(path);

        float width = bm.getWidth();
        float height = bm.getHeight();
        float etWidth = message_text.getWidth();
        float etHeight = message_text.getHeight();
        float Pwidth = width;
        float Pheight = height;
        if(width>etWidth-20){
            //图片太宽

            width = etWidth-20;
            //等比例缩放
            height = height * width / Pwidth;
            opt.inSampleSize = (int)(Pwidth / width);
        }
        if(height>etHeight-20){
            //图片太长

            height = etHeight-20;
            //等比例缩放
            width = width * height / Pheight;
            opt.inSampleSize = (int)(Pheight / height);
        }

        //加载缩放图片
        opt.inJustDecodeBounds = false;
        bm = BitmapFactory.decodeFile(path, opt);
        return bm;
    }

    public class postThread extends Thread  {
        //post请求
        private String path;
        private Context context;
        private String params;
        private Handler handler;
        private int what;
        public postThread(String path,Context context,String params,Handler handler,int what){
            super();
            this.path=path;
            this.context=context;
            this.params=params;
            this.handler=handler;
            this.what=what;
        }

        @Override
        public void run() {
            try {
                String urlString = context.getResources().getString(R.string.serverURL);
                urlString+=path;
                URL url = new URL(urlString);
                // url.openConnection()打开网络链接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Accept-Charset", "utf-8");
                connection.setRequestProperty("Connection", "keep-alive");
                connection.getOutputStream().write(params.getBytes());
                String jsonString="";
                if (connection.getResponseCode() == 200) {
                    InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    jsonString = "";
                    String readline = null;
                    while ((readline = bufferedReader.readLine()) != null) {
                        jsonString += readline;
                    }
                    inputStreamReader.close();

                    //传递信息
                    Message json = handler.obtainMessage();
                    json.obj = jsonString;
                    json.what = what;
                    handler.sendMessage(json);
                } else {
                    System.out.println("------------------链接失败-----------------");
                    handler.sendEmptyMessage(0);
                }
            } catch (Exception e) {
                handler.sendEmptyMessage(0);
                e.printStackTrace();
            }
            super.run();
        }
    }

    public class uploadFileThread extends Thread {
        //post请求
        private String path;
        private JSONObject filePath;
        private Context context;
        private Handler handler;
        private int what;
        public uploadFileThread(String path,Context context,JSONObject filePath,Handler handler,int what){
            super();
            this.path=path;
            this.context=context;
            this.filePath=filePath;
            this.handler=handler;
            this.what=what;
        }

        private  final String TAG = "uploadFile";
        private  final int TIME_OUT = 10*1000000; //超时时间
        private  final String CHARSET = "utf-8"; //设置编码
        private  final String BOUNDARY = "--------------"+ UUID.randomUUID().toString(); //边界标识 随机生成
        private  final String PREFIX="--";
        private  final String LINE_END="\r\n";
        private  final String CONTENT_TYPE = "multipart/form-data"; //内容类型
        @Override
        public void run() {
            try {
                String urlString = context.getResources().getString(R.string.serverURL);
                urlString+=path;
                URL url = new URL(urlString);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(TIME_OUT);
                conn.setConnectTimeout(TIME_OUT);
                conn.setDoInput(true); //允许输入流
                conn.setDoOutput(true); //允许输出流
                conn.setUseCaches(false); //不允许使用缓存
                conn.setRequestMethod("POST"); //请求方式
                conn.setRequestProperty("Charset", CHARSET);//设置编码
                //头信息
                conn.setRequestProperty("Connection", "keep-alive");
                conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
                OutputStream outputSteam=conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                //逐个文件拼接
                int i = 0;
                Iterator it = filePath.keys();
                while (it.hasNext()){
                    String src = it.next().toString();
                    String alt = filePath.getString(src);
                    File file = new File(src);
                    if(file!=null){
                        StringBuffer sb = new StringBuffer();
                        //添加分割边界
                        //上传file手机本地地址
                        sb.append(PREFIX);
                        sb.append(BOUNDARY);
                        sb.append(LINE_END);
                        sb.append("Content-Disposition: form-data; name=\"localurl[" + i + "]\"" +LINE_END);
                        sb.append(LINE_END);
                        sb.append(src);
                        sb.append(LINE_END);
                        //dos.write(sb.toString().getBytes());
                        //file内容
                        sb.append(PREFIX);
                        sb.append(BOUNDARY);
                        sb.append(LINE_END);
                        sb.append("Content-Disposition: form-data; name=\"file[" + i + "]\";filename=" + "\"" + file.getName() + "\"" + LINE_END);
                        sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
                        //sb.append("Content-Transfer-Encoding: binary"+LINE_END);
                        sb.append(LINE_END);
                        dos.write(sb.toString().getBytes());
                        //读取文件的内容
                        DataInputStream is = new DataInputStream(new FileInputStream(file))  ;
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        while((len=is.read(bytes))!=-1)
                        {
                            dos.write(bytes, 0, len);
                        }
                        dos.write((" "+alt).getBytes());
                        //dos.write(" [apple]".getBytes());
                        is.close();
                        //写入文件二进制内容
                        dos.write(LINE_END.getBytes());
                    }else{
                        Toast.makeText(context, src+" 文件不存在", Toast.LENGTH_SHORT).show();
                        return ;
                    }
                    i++;
                }
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                String jsonString;
                if (conn.getResponseCode() == 200) {
                    InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream());
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    jsonString = "";
                    String readline = null;
                    while ((readline = bufferedReader.readLine()) != null) {
                        jsonString += readline;
                    }
                    inputStreamReader.close();

                    //传递信息
                    Message json = handler.obtainMessage();
                    json.obj = jsonString;
                    json.what = what;
                    handler.sendMessage(json);
                } else {
                    System.out.println("------------------链接失败-----------------");
                    handler.sendEmptyMessage(0);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }catch (JSONException e){
                e.printStackTrace();
            }
            super.run();

        }
    }

    public class downloadFileThread extends Thread  {
        //下载文件
        private String id;
        private String path;
        private Handler handler;
        private int what;
        public downloadFileThread(String id,String path,Handler handler,int what){
            super();
            this.id = id;
            this.path = path;
            this.handler = handler;
            this.what = what;
        }

        @Override
        public void run() {
            try {
                //获取文件名及后缀
                String name = path.substring(path.lastIndexOf("/"));
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(Environment.getExternalStorageDirectory())
                        .append("/secret/")
                        .append(id)
                        .append("/pic");
                //创建文件夹
                File folder=new File(stringBuilder.toString());
                if(!folder.exists()){
                    folder.mkdirs();
                }
                stringBuilder.append(name);
                File file=new File(stringBuilder.toString());
                //文件不存在时再下载
                if(!file.exists()) {
                    //对资源链接
                    file.createNewFile();
                    URL url = new URL(path);
                    //打开输入流
                    InputStream inputStream = url.openStream();
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    int hasRead = 0;
                    while ((hasRead = inputStream.read()) != -1) {
                        fileOutputStream.write(hasRead);
                    }
                    fileOutputStream.close();
                    inputStream.close();
                    handler.sendEmptyMessage(what+1);
                }


                handler.sendEmptyMessage(what);
            }catch (Exception e){
                e.printStackTrace();
                handler.sendEmptyMessage(0);
            }
            super.run();
        }
    }

}
